package com.itheima.controller;

import com.itheima.dao.UserMapper;
import com.itheima.domain.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @GetMapping("/loginOut")
    public String login() {
        return "login";
    }
    @PostMapping("/loginServlet")
    public ModelAndView loginServlet(String username, String password, HttpSession session, Model model) {
        System.out.println("username="+username+ password);
        if (username == null || username.isEmpty() || password == null || password.isEmpty()) {
            model.addAttribute("msg", "用户名或密码不能为空");
            return new ModelAndView("login", model.asMap());
        }
        User user = userService.findByUsername(username);
        if (user != null) {
            if (user.getPassword().equals(password)) {
                ModelAndView modelAndView = new ModelAndView("index");
                modelAndView.addObject("user", user);
                session.setAttribute("user",user);
                System.out.println("登录成功");
                return modelAndView;
            } else {
                System.out.println("密码错误");
                model.addAttribute("msg", "密码错误");
                return new ModelAndView("login", model.asMap());
            }
        } else {
            System.out.println("用户不存在");
            model.addAttribute("msg", "用户不存在");
            return new ModelAndView("login", model.asMap());
        }

    }
    @PostMapping("/register")
    public ModelAndView register(String username, String password,String nickname, String rePassword) {
        System.out.println("注册的user="+username);
        ModelAndView model = new ModelAndView("regist");
        User user = userService.findByUsername(username);
        if (user != null) {
            model.addObject("msg", "用户已存在");
            return model;
        }
        if (username == null) {
            model.addObject("msg", "账号不能为空");
            return model;
        }
        if (password == null || !password.equals(rePassword)) {
            model.addObject("msg", "密码不匹配");
            return model;
        }
        userService.register(username, password,nickname);
        model.addObject("msg", "注册成功");
        return model;
    }

}
